package com.weme.mine.view

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView


class DrawableRightTextView : AppCompatTextView {
    init {
        val drawables = compoundDrawables
        val drawableRight = drawables[2] // 假设 drawableRight 在数组的第三个位置
        drawableRight.setBounds(0,0,resources.getDimension(com.example.resources.R.dimen.dp_7).toInt(),resources.getDimension(com.example.resources.R.dimen.dp_12).toInt())

        setCompoundDrawables(null, null, drawableRight, null)
    }
    constructor(context: Context?) : super(context!!) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context!!, attrs, defStyleAttr) {
        init()
    }

    private fun init() { // Add a TextWatcher to monitor text changes
        addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                updateDrawableRightVisibility()
            }

            override fun afterTextChanged(s: Editable) {}
        }) // Set the initial visibility of drawableRight
        updateDrawableRightVisibility()
    }

    fun clearDrawableRight() {
        setCompoundDrawables(null, null, null, null)

    }
    // Method to toggle the visibility of drawableRight based on text
    private fun updateDrawableRightVisibility() {
        val drawables = compoundDrawables
        val drawableRight = drawables[2] // 假设 drawableRight 在数组的第三个位置

        if (drawableRight != null) {
            if (text != null && text.isNotEmpty()) {
                drawableRight.setVisible(true, false)
                drawableRight.setBounds(0,0,resources.getDimension(com.example.resources.R.dimen.dp_7).toInt(),resources.getDimension(com.example.resources.R.dimen.dp_12).toInt())

                setCompoundDrawables(null, null, drawableRight, null)
            } else {
                drawableRight.setVisible(false, false)
            }
        }
    }
}
